package com.qfedu.fmmall.service.impl;

import com.qfedu.fmmall.dao.UsersMapper;
import com.qfedu.fmmall.entity.Users;
import com.qfedu.fmmall.service.UserService;
import com.qfedu.fmmall.utils.Base64Utils;
import com.qfedu.fmmall.utils.MD5Utils;
import com.qfedu.fmmall.vo.ResStatus;
import com.qfedu.fmmall.vo.ResultVO;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    @Transactional
    public ResultVO userResgit(String username, String password) {
        synchronized (this) {
            //1.根据用户名查询，这个用户是否已经被注册
            Example example = new Example(Users.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("username", username);
            Users user = usersMapper.selectOneByExample(example);
            //2.如果没有被注册，则进行保存操作
            if (user == null) {
                user = new Users();
                //密码加密保存
                String md5Pwd = MD5Utils.md5(password);
                user.setUsername(username);
                user.setPassword(md5Pwd);
                user.setUserImg("img/default.png");
                user.setUserRegtime(new Date());
                user.setUserModtime(new Date());
                int i = usersMapper.insertUseGeneratedKeys(user);
                if (i > 0) {
                    return new ResultVO(ResStatus.OK.getCode(), "注册成功！", user);
                } else {
                    return new ResultVO(ResStatus.NO.getCode(), "注册失败！", null);
                }
            } else {
                return new ResultVO(ResStatus.NO.getCode(), "用户名已经被注册！", null);
            }
        }
    }

    @Override
    public ResultVO checkLogin(String username, String password) {
//        1.根据账号查询用户信息
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        Users user = usersMapper.selectOneByExample(example);
        if (user == null) {
            //用户名不存在
            return new ResultVO(ResStatus.NO.getCode(), "登录失败！用户名不存在", null);
        } else {
            //对输入的密码pwd进行加密
            //使用加密后的密码和user的密码进行匹配
            if (user.getPassword().equals(MD5Utils.md5(password))) {
                //验证成功
                //如果登陆验证成功，则需要生成token令牌,使用jwt规则
//              String token = Base64Utils.encode(username + 123456);
                JwtBuilder builder = Jwts.builder();
                HashMap<String, Object> map = new HashMap<>();
                map.put("key1","value1");
                map.put("key2","value2");
                String token = builder.setSubject(username)//主题就是token中携带的数据
                        .setIssuedAt(new Date())//设置token的生成时间
                        .setId(user.getUserId() + "")//设置用户id为token的id
                        .addClaims(map)// map中可以存放用户的角色权限信息
                        .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))//设置token的过期时间
                        .signWith(SignatureAlgorithm.HS256, "123456")//设置加密方式和加密密码
                        .compact();
                return new ResultVO(ResStatus.OK.getCode(), token, user);
            } else {
                //密码错误
                return new ResultVO(ResStatus.NO.getCode(), "登录失败！密码错误", null);
            }
        }
    }

}
